﻿using AdinZ.DB;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;


/**
* @Author: AdinZ
* @Q  Q : 1454269
* @Email:adinz@adinz.com
* @Created: 2014/3/30 11:18:55
*
* */
namespace Reader.Api
{
    public class DB
    {
        static Novel.Sys.BLL.novel_article __bll_art = new Novel.Sys.BLL.novel_article();
        static Novel.Sys.BLL.novel_chapter __bll_chap = new Novel.Sys.BLL.novel_chapter();
        static Novel.Sys.BLL.novel_sort __bll_sort = new Novel.Sys.BLL.novel_sort();
        static Novel.Sys.BLL.novel_search __bll_search = new Novel.Sys.BLL.novel_search();
        static Novel.Sys.BLL.novel_session __bll_session = new Novel.Sys.BLL.novel_session();
        static Novel.Sys.BLL.novel_user __bll_user = new Novel.Sys.BLL.novel_user();
        static Novel.Sys.BLL.novel_user_info __bll_info = new Novel.Sys.BLL.novel_user_info();
        static Novel.Sys.BLL.novel_book_orders __bll_orders = new Novel.Sys.BLL.novel_book_orders();
        static Novel.Sys.BLL.novel_topic __bll_topic = new Novel.Sys.BLL.novel_topic();
        static Novel.Sys.BLL.novel_recharge __bll_recharge = new Novel.Sys.BLL.novel_recharge();
        static Novel.Sys.BLL.novel_checkin __bll_check = new Novel.Sys.BLL.novel_checkin();
        static Novel.Sys.BLL.novel_ads __bll_ads = new Novel.Sys.BLL.novel_ads();
        static Novel.Sys.BLL.novel_push_bookcase __bll_push_book = new Novel.Sys.BLL.novel_push_bookcase();
        static Novel.Sys.BLL.novel_location __bll_local = new Novel.Sys.BLL.novel_location();

        public static DataSet getUpdate(string type)
        {
            string sql = "SELECT TOP 1 * FROM  [reader_update] WHERE [type] ='" + type
                    + "' ORDER BY  ID desc";
            return DbHelpers.GetDataSet(sql);
        }

        public static DataSet getMessage(string type)
        {
            string sql = "SELECT TOP 1 * FROM  [reader_message] WHERE [type] ='" + type
                    + "'  ORDER BY  ID desc";
            return DbHelpers.GetDataSet(sql);
        }

        public static DataSet getMessage(string type, int id)
        {
            string sql = "SELECT TOP 1 * FROM  [reader_message] WHERE [type] ='" + type
        + "' AND id="+id+"  ORDER BY  ID desc";
            return DbHelpers.GetDataSet(sql);
        }


        public static bool isExistInstall(string imei, string type)
        {
            string sql = "SELECT count(*) FROM   [reader_install] WHERE [type]='" + type
                    + "' AND [imei]='" + imei + "'";
            return DbHelpers.Exists(sql);
        }

        public static int addInstall(string type, string imei, string version, string model, string os, string os_name, string screen_size, string cu, string Agent, string vid, string pid, string firm, string kernel)
        {
            string sql = "INSERT INTO [reader_install] ([type], [imei], [version], [model], [SDK], [os_ver], [screen_size], [times],[cu],[Agent],[vid],[pid],[firm],[kernel]) VALUES ('"
                    + type
                    + "', '"
                    + imei
                    + "', '"
                    + version
                    + "', '"
                    + model
                    + "', '"
                    + os + "', '" + os_name + "', '" + screen_size + "', '" + DateTime.Now + "','" + cu + "','" + Agent + "','" + vid + "','" + pid + "','" + firm + "','" + kernel + "')";
            return DbHelpers.NonQuery(sql);
        }

        /// <summary>
        /// 获取特荐
        /// </summary>
        /// <param name="page"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        public static DataSet GetRecommend(int page,int pageSize)
        {
            return __bll_art.GetListByPage(" [recommend]=1 AND [display]=1 ", " ID Desc", (page - 1) * pageSize, page * pageSize);
        }

        public static DataSet GetSortList(int tid, int page, int pageSize)
        {
            return __bll_art.GetListByPage(" [tid]="+tid, " ID Desc", (page - 1) * pageSize, page * pageSize);
        }
        public static string GetSortName(int tid) { return __bll_sort.GetSortName(tid); }

        public static DataSet GeTopicList(int tid, int page, int pageSize)
        {
            return __bll_art.GetListByPage(" [topicid]=" + tid + " AND [display]=1 ", " ID Desc", (page - 1) * pageSize, page * pageSize);
        }


        public static Novel.Sys.Model.novel_article GetBookInfo(int id)
        {
            return __bll_art.GetModel(id);
        }

        public static DataSet GetChapterList(int id,int page,int pagesize,string OrderBy)
        {
            return __bll_chap.GetListByPage(" [local]=1 And [aid]=" + id, OrderBy, (page - 1) * pagesize, page * pagesize);
        }
        public static int GetChapterCount(int Id)
        {
            return __bll_chap.GetCount(Id);
        }

        public static int SetDownloads(int id)
        {
            int num = __bll_art.GetDownloads(id) + 1;
            __bll_art.UpdateDownloads(id, num);
            return num;
        }

        public static int SetHits(int id)
        {
            int num = __bll_art.GetHits(id) + 1;
            __bll_art.UpdateHits(id, num);
            return num;
        }

        public static DataSet GetSortTopic(int id)
        {
            return __bll_art.GetListByPage(" [display]=1 AND  [strong]=1 And [tid]= " + id, " ID Desc", 0, 4);
        }
        public static DataSet GetSearch(string key, int page, int pageSize)
        {
            string vSqlWhere = "[Display]=1";
            vSqlWhere += " And [title] Like '%" + key + "%' OR author LIKE '%" + key + "%' OR intor LIKE '%" + key + "%'";

            DataSet ds = __bll_art.GetListByPage(vSqlWhere, " ID Desc", (page - 1) * pageSize, page * pageSize);
            return ds;
        }

        public static int addSearch(string Key)
        {
            if (__bll_search.Exists(Key))
            {
                int count = __bll_search.GetCount(Key);
                return __bll_search.UpdateCount(Key, count + 1);
            }
            else
            {
              return  __bll_search.AddKey(Key);
            }
        }

        public static DataSet GetTag(int size)
        {
            //select top 50 * FROM novel_search order by [count] desc
            return __bll_search.GetListByPage("", " [count] desc", 0, size);
        }
        public static Novel.Sys.Model.novel_chapter GetChapter(int chapterid)
        {
            return __bll_chap.GetModel(chapterid);
        }
        public static Novel.Sys.Model.novel_user_info GetUser(int id, string Session)
        {
            if (__bll_session.Exists(id, Session))
            {
                return __bll_info.GetModel(id, Session);
  
            }
            else return null;
        }
        public static Novel.Sys.Model.novel_user_info GetUserInfo(int uid)
        {
            return __bll_info.GetModel(uid);
        }

        public static bool Pay(int uid, float payment, int bookid, long chapterId)
        {
            Novel.Sys.Model.novel_book_orders model = new Novel.Sys.Model.novel_book_orders();
            model.Uid = uid;
            model.BookId = bookid;
            model.ChapterId = chapterId;
            model.Payment = payment;
            model.Price = payment;
            model.Status = 1;
            model.Time = DateTime.Now;
            string StrMoney = __bll_info.GetWhere("[uid]='" + uid + "' ", " money ");
            if (payment <= float.Parse(StrMoney))
            {
                if (__bll_orders.Add(model) > 0)
                {
                    return __bll_info.UpdateMoney(uid, payment, true);
                }
                else { return false; }
            }
            else { return false; }
        }


        public static bool Recharge(int uid, float payment, string type)
        {
            Novel.Sys.Model.novel_recharge model = new Novel.Sys.Model.novel_recharge();
            model.Uid = uid;
            model.Payment = payment;
            model.PayTime = DateTime.Now;
            model.Payment = payment;
            model.Type = type;
            model.OrdID = DateTime.Now.ToString("yyyyMMddhhmmss");
            if (__bll_recharge.Add(model) > 0)
            {
                return __bll_info.UpdateMoney(uid, payment, false);
            }
            else { return false; }
        }
        public static bool Recharge(int uid, float payment, string type,string intor,string ordId)
        {
            Novel.Sys.Model.novel_recharge model = new Novel.Sys.Model.novel_recharge();
            model.Uid = uid;
            model.Payment = payment;
            model.PayTime = DateTime.Now;
            model.Payment = payment;
            model.Intor = intor;
            model.Type = type;
            model.OrdID = ordId;
            if (__bll_recharge.Add(model) > 0)
            {
                return __bll_info.UpdateMoney(uid, payment, false);
            }
            else { return false; }
        }

        public static bool isOrdID(int UID, string OrdId)
        {
            return __bll_recharge.Exists(UID, OrdId);
        }

        public static bool PlugRecharge(string imei, float payment,string type,string intor)
        {
            int uid = __bll_info.ImeiGetUid(imei);
            if (uid < 1) return false;
            Novel.Sys.Model.novel_recharge model = new Novel.Sys.Model.novel_recharge();
            model.Uid = uid;
            model.Payment = payment;
            model.PayTime = DateTime.Now;
            model.Payment = payment;
            model.Type = type;
            model.Intor = intor;
            if (__bll_recharge.Add(model) > 0)
            {
                return __bll_info.UpdateMoney(uid, payment, false);
            }
            else { return false; }
        }



        public static bool isOrders(int uid, int bookId)
        {
            return __bll_orders.Exists(uid, bookId);
        }

        public static Novel.Sys.Model.novel_user_info Login(string name, string passwd)
        {
          string md5Passwd=  AdinZ.Common.EncryAndDecry.EncryMd5(passwd, true, true);
          Novel.Sys.Model.novel_user_info user = new Novel.Sys.Model.novel_user_info();
          Novel.Sys.Model.novel_session Session = new Novel.Sys.Model.novel_session();

            if (__bll_user.Exists(name, md5Passwd))
            {
                string session = AdinZ.Common.EncryAndDecry.EncryMd5(md5Passwd+passwd+DateTime.Now, true, true);
                user.User = __bll_user.GetModel(name);
                if (user.User != null)
                {
                    if (__bll_session.Exists(user.User.ID)) { __bll_session.UpdateSession(user.User.ID, session, DateTime.Now.AddDays(30)); }
                    else {
                        Session.Uid = user.User.ID;
                        Session.Session = session;
                        Session.Created = DateTime.Now;
                        Session.Endtime = DateTime.Now.AddDays(30);
                        __bll_session.Add(Session);
                    }
                }
                
            }
            else { return null; }
            user = __bll_info.GetModel(user.User.ID);
            if (user != null)
                return user;
            else
                return null;
        }

        public static Novel.Sys.Model.novel_user_info Login(string imei)
        {
            Novel.Sys.Model.novel_user_info user = new Novel.Sys.Model.novel_user_info();
            Novel.Sys.Model.novel_session Session = new Novel.Sys.Model.novel_session();
            int UID = __bll_info.ImeiGetUid(imei);
            if (UID > 0)
            {
                string session = AdinZ.Common.EncryAndDecry.EncryMd5(UID + "dsjkjs" + DateTime.Now, true, true);
                if (__bll_session.Exists(UID)) { __bll_session.UpdateSession(UID, session, DateTime.Now.AddDays(30)); }
                else
                {
                    Session.Uid = user.User.ID;
                    Session.Session = session;
                    Session.Created = DateTime.Now;
                    Session.Endtime = DateTime.Now.AddDays(30);
                    __bll_session.Add(Session);
                }

                user = __bll_info.GetModel(UID);
                return user;
            }
            else return null;
        }


        public static int Register(string name, string passwd, string email, string phone, string imei)
        {

            if (!__bll_user.Exists(name))
            {
                if (!__bll_info.Exists(imei))
                {
                    Random r = new Random();
                    int random = r.Next(1, 40);
                    Novel.Sys.Model.novel_user_info Info = new Novel.Sys.Model.novel_user_info();
                    Novel.Sys.Model.novel_user User = new Novel.Sys.Model.novel_user();
                    Novel.Sys.Model.novel_session Session = new Novel.Sys.Model.novel_session();
                    int uid = 0;
                    #region User_User
                    User.Avatar = "avatar/avatar_" + random + ".jpg";
                    User.Email = email;
                    User.Name = name;
                    User.Passwd = AdinZ.Common.EncryAndDecry.EncryMd5(passwd, true, true);
                    User.Phone = phone;
                    User.Sex = 1;
                    User.Nick = "";
                    User.Gid = 1;
                    #endregion
                    uid = __bll_user.Add(User);
                    if (uid < 0) { return 11;/*用户注册成功添加详细失败*/ }
                    #region User_Info
                    Info.Uid = uid;
                    Info.Gold = 0.0f;
                    Info.Imei = imei;
                    try { Info.Money = float.Parse(AdinZ.Common.ConfigHelper.ReadSettings("RegisterMoney")); }
                    catch { Info.Money = 0.0f; }
                    Info.Signature = "你还没有写签名!";
                    #endregion
                    __bll_info.Add(Info);

                    Session.Uid = uid;
                    Session.Session = "not";
                    Session.Created = DateTime.Now;
                    Session.Endtime = DateTime.Now;
                    __bll_session.Add(Session);
                    return 0;
                }
                else { return 7; }
            }
            else
            {
                return 10;//用户名已存在
            }
        }




        public static DataSet GetTopic()
        {
            return __bll_topic.GetListByPage("1=1", " ID Desc", 0, 4);
        }

        public static float GetBookPrice(int ID,long chapterid)
        {
            return __bll_art.GetBookPrice(ID,chapterid);
        }
        public static int GetChapterNum(long Id)
        {
            return __bll_chap.GetChapterNum(Id);
        }

        public static DataSet GetChapter(int bookId, int startChapterNum, int endChapterNum)
        {
            return __bll_chap.GetChapter(bookId, startChapterNum, endChapterNum);
        }



        public static bool CheckIn(int Uid,float money)
        {
            string mark = DateTime.Now.ToString("yyyyMMdd");
            if (!__bll_check.Exists(Uid, mark))
            {
                Novel.Sys.Model.novel_checkin model = new Novel.Sys.Model.novel_checkin();
                model.Uid = Uid;
                model.Time = DateTime.Now;
                model.Award = money;
                model.Mark = mark;
                __bll_check.Add(model);//添加签到记录
                __bll_info.UpdateMoney(Uid, money, false);//给账号充钱
                return true;
            }
            else { return false; }
           
        }
        public static int GetCheckCount(int Uid)
        {
            return __bll_check.GetCount(Uid);
        }


        public static string GetRandomAds()
        {
            string tem= __bll_ads.GetModel(5).Content;
            if (string.IsNullOrEmpty(tem))
            {
                return "[广告位] 我在这里等你很久了亲<a href='http://www.xiaoshuofang.com'>href...</a>";
            }
            else
            {
                return tem;
            }
        }

        public static DataSet GetPushBookId()
        {
            return __bll_push_book.GetList(" type=0 ");
        }
        public static DataSet GetBookList(string id)
        {
            return __bll_art.GetListID(id);
        }

        public static bool LocalExistsImei(string IMEI)
        {
            return __bll_local.Exists(IMEI);
        }
        public static bool LocalExistsID(int ID)
        {
            return __bll_local.Exists(ID);
        }
        public static Novel.Sys.Model.novel_location LocalModel(string IMEI)
        {
            return __bll_local.GetModel(IMEI);
        }
        public static int LocalUpdate(Novel.Sys.Model.novel_location model)
        {
            return __bll_local.Update(model);
        }
        public static int LocalAdd(Novel.Sys.Model.novel_location model)
        {
            return __bll_local.Add(model);
        }

    }
}
